package com.sc.auction.common.jwt;

import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtils {
    /**
     * 生成Jwt令牌
     * @param user
     * @return
     */
    public static final String APP_SECRET="000000";
    public static final long EXPIRE = 1000 * 60 * 30;
    public static String genJwt(JwtInfo jwtInfo){
        //创建JwtBuilder对象
        JwtBuilder builder = Jwts.builder();
        //第一部分：JWT头
        builder.setHeaderParam("alg","HS256");//设置签名算法
        builder.setHeaderParam("type","JWT");//设置令牌类型
        //第二部分：有效载荷
        builder.setId("1");
        builder.setSubject("auction-user");
        builder.setIssuedAt(new Date());
        builder.setExpiration(new Date(System.currentTimeMillis()+EXPIRE));
        //私有字段
        builder.claim("userCode",jwtInfo.getUserCode());
        builder.claim("id",jwtInfo.getId());
        //第三部分：签名哈希
        builder.signWith(SignatureAlgorithm.HS256, APP_SECRET);
        String token=builder.compact();
        return token;
    }
    /**
     * 解析jwt的方法
     * @param token
     * @return
     */
    public static Claims checkJwt(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body;
    }
}
